<?php

// Function Make the request to amazon and return the XML response
// a Responses here: http://associates-amazon.s3.amazonaws.com/signed-requests/helper/index.html
function bc_amazon_request($region, $params, $public_key, $private_key, $associate_tag) {   
    
/*
    Parameters:
        $region - the Amazon(r) region (ca,com,co.uk,de,fr,jp)
        $params - an array of parameters, eg. array("Operation"=>"ItemLookup",
                        "ItemId"=>"B000X9FLKM", "ResponseGroup"=>"Small")
        $public_key - your "Access Key ID"
        $private_key - your "Secret Access Key"
    */

    // some paramters
    $method = "GET";
    $host = "ecs.amazonaws.".$region;
    $uri = "/onca/xml";
    
    // additional parameters
    $params["Service"] = "AWSECommerceService";
    $params["AWSAccessKeyId"] = $public_key;
    // GMT timestamp
    $params["Timestamp"] = gmdate("Y-m-d\TH:i:s\Z");
    // API version
    $params["Version"] = "2011-08-01";
	$params["AssociateTag"] = $associate_tag;
	
	// If what we are looking for is a book then 
	// IdType = isbn and SearchIndex = books
	// Otherwise don't specify an IdType and SearchIndex = all
	
	if (bc_isbn_test($params['Keywords']) == True) {
		// Clean up ISBN
		$params["Keywords"] = bc_isbn_validator($params['Keywords']);
		$params["IdType"] = "ISBN";
		$params["SearchIndex"] = "Books";
	}
	else {
		$params["IdType"] = "";
		$params["SearchIndex"] = "All";
	}
	
    // sort the parameters
    ksort($params);
    
    // create the canonicalized query
    $canonicalized_query = array();
    foreach ($params as $param=>$value)
    {
        $param = str_replace("%7E", "~", rawurlencode($param));
        $value = str_replace("%7E", "~", rawurlencode($value));
        $canonicalized_query[] = $param."=".$value;
    }
    $canonicalized_query = implode("&", $canonicalized_query);
    
    // create the string to sign
    $string_to_sign = $method."\n".$host."\n".$uri."\n".$canonicalized_query;
    
    // calculate HMAC with SHA256 and base64-encoding
    $signature = base64_encode(hash_hmac("sha256", $string_to_sign, $private_key, True));
    
    // encode the signature for the request
    $signature = str_replace("%7E", "~", rawurlencode($signature));
    
    // create request
    $request = "http://".$host.$uri."?".$canonicalized_query."&Signature=".$signature;
    
	//echo $request; 
	
    // do request
    $response = @file_get_contents($request);
    
	// echo "<br /><br />" . $request . "<br /><br />";
	
    if ($response === False)
    {
        return False;
    }
    else
    {
        // parse XML
        $pxml = simplexml_load_string($response);
        if ($pxml === False)
        {
            return False; // no xml
        }
        else
        {
            return $pxml;
        }
    }
}

// Takes the list of paramaters and removes the potential '-' from a 13 digit isbn
function bc_isbn_validator($isbn) {
	$isbn = str_replace('-', '', $isbn);
	$isbn = str_replace(' ', '', $isbn);
	return $isbn;	
}


// Called from bc_amazon_price_gen() returns the price values in an array
function bc_amazon_price($region, $params, $public_key, $private_key, $associate_tag) {
	
	// Set Price Specific Paramaters
	$params["ResponseGroup"] = "Offers";
	//$params["ResponseGroup"] = "ItemAttributes";

	$pxml = bc_amazon_request($region, $params, $public_key, $private_key, $associate_tag);
	
	$price_info = array();
	
	
	if ($pxml === False) {
	    return False;
	}
	else {
		// Get the three types of prices from the xml data.
		
		if (isset($pxml->Items->Item->OfferSummary->LowestNewPrice->FormattedPrice))
			$amazon_price['LowestNewPrice'] = $pxml->Items->Item->OfferSummary->LowestNewPrice->FormattedPrice;
			
		if(isset($pxml->Items->Item->OfferSummary->LowestUsedPrice->FormattedPrice))
			$amazon_price['LowestUsedPrice'] = $pxml->Items->Item->OfferSummary->LowestUsedPrice->FormattedPrice;
		
		if(isset($pxml->Items->Item->OfferSummary->LowestCollectiblePrice->FormattedPrice))
			$amazon_price['LowestCollectiblePrice'] = $pxml->Items->Item->OfferSummary->LowestCollectiblePrice->FormattedPrice;
		
		if (isset($amazon_price['LowestNewPrice']))
			return $amazon_price;
		else
			return False;
	}
}

// Called from bc_amazon_search_price_gen() returns the price values in an array
function bc_amazon_search_price($region, $params, $public_key, $private_key, $associate_tag) {
	
	// Set Price Specific Paramaters
	$params["ResponseGroup"] = "Offers";

	$pxml = bc_amazon_request($region, $params, $public_key, $private_key, $associate_tag);
	
	$price_info = array();
	
	if ($pxml === False) {
	    return False;
	}
	else {
		// Sort Data, Get the first 10 results and their urls/prices/asin
		$i = 0;
		while ($i != 10) {
			$results_array = array();
			// Get the Prices
			if(isset($pxml->Items->Item[$i]->OfferSummary->LowestNewPrice->FormattedPrice))
				$results_array['LowestNewPrice'] = $pxml->Items->Item[$i]->OfferSummary->LowestNewPrice->FormattedPrice;
			if(isset($pxml->Items->Item[$i]->OfferSummary->LowestUsedPrice->FormattedPrice))
				$results_array['LowestUsedPrice'] = $pxml->Items->Item[$i]->OfferSummary->LowestUsedPrice->FormattedPrice;
			if(isset($pxml->Items->Item[$i]->OfferSummary->LowestCollectiblePrice->FormattedPrice))
				$results_array['LowestCollectiblePrice'] = $pxml->Items->Item[$i]->OfferSummary->LowestCollectiblePrice->FormattedPrice;
			
			// Get ASIN
			if(isset($pxml->Items->Item[$i]->ASIN))
				$results_array['ASIN'] = $pxml->Items->Item[$i]->ASIN;
			
			// Add Results to price_info
			$price_info[$i] = $results_array;
			
			$i += 1;
		}
		
		return $price_info;
		
	}
}

// Called from bc_amazon_details_gen() returns the detail values in an array
function bc_amazon_details($region, $params, $public_key, $private_key, $associate_tag) {
	
	$pxml = bc_amazon_request($region, $params, $public_key, $private_key, $associate_tag);
	
	$amazon_details = array();
	
	
	if ($pxml === False) {
	    return False;
	}
	else {
		// Get the three types of prices from the xml data.
		if($pxml->Items->Request->IsValid != 'True') {
			return False;
		}
		else {
			if (isset($pxml->Items->Item->DetailPageURL))
				$amazon_details['DetailPageURL'] = $pxml->Items->Item->DetailPageURL;
				
			if (isset($pxml->Items->Item->ItemAttributes->Author))
				$amazon_details['Author'] = $pxml->Items->Item->ItemAttributes->Author;

			if (isset($pxml->Items->Item->ItemAttributes->Manufacturer))
				$amazon_details['Manufacturer'] = $pxml->Items->Item->ItemAttributes->Manufacturer;

			if (isset($pxml->Items->Item->ItemAttributes->ProductGroup))
				$amazon_details['ProductGroup'] = $pxml->Items->Item->ItemAttributes->ProductGroup;
				
			if (isset($pxml->Items->Item->ItemAttributes->Title))
				$amazon_details['Title'] = $pxml->Items->Item->ItemAttributes->Title;
			
			return $amazon_details;
		}
		
	}
}

// Called from bc_amazon_image_gen() returns the image values in an array
function bc_amazon_images($region, $params, $public_key, $private_key, $associate_tag) {

	// Set Images Specific Paramaters
	$params["ResponseGroup"] = "Images";
	
	$pxml = bc_amazon_request($region, $params, $public_key, $private_key, $associate_tag);

	$amazon_images = array();


	if ($pxml === False) {
	    return False;
	}
	else {
		// Get the three types of prices from the xml data.

		if($pxml->Items->Request->IsValid != 'True') {
			return False;
		}
		else {
			if (isset($pxml->Items->Item->SmallImage->URL))
				$amazon_images['SmallImage'] = $pxml->Items->Item->SmallImage->URL;

			if (isset($pxml->Items->Item->MediumImage->URL))
				$amazon_images['MediumImage'] = $pxml->Items->Item->MediumImage->URL;

			if (isset($pxml->Items->Item->LargeImage->URL))
				$amazon_images['LargeImage'] = $pxml->Items->Item->LargeImage->URL;

			return $amazon_images;
		}

	}
}

// Called from bc_amazon_attributes_gen() returns the price values in an array
function bc_amazon_attributes($region, $params, $public_key, $private_key, $associate_tag) {
	
	// Set Price Specific Paramaters
	$params["ResponseGroup"] = "ItemAttributes";

	$pxml = bc_amazon_request($region, $params, $public_key, $private_key, $associate_tag);
		
	if ($pxml === False) {
	    return False;
	}
	else {
		// Get the UPC from the xml
		if (isset($pxml->Items->Item->ItemAttributes->UPC))
			$UPC = $pxml->Items->Item->ItemAttributes->UPC;
			
			//$UPC = $pxml->Items->Item->ItemAttributes->UPCList->UPCListElement[1];
		if (isset($UPC))
			return $UPC;
		else
			return False;
	}
}

?>